package com.onpositive.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.onpositive.notes.model.INote;
import com.onpositive.notes.model.ITemplate;
import com.onpositive.notes.services.BasicCollectionRegistry;
import com.onpositive.notes.services.BasicNoteRegistry;

public class Delta<T> implements ICollectionDelta<T> {

	private static final long serialVersionUID = 3341546590513986043L;
	
	public Delta(){}
	
	public Delta(
			Class<T> clazz,
			int templateId,
			List<Integer> idList,
			List<T> valuesList) {
		
		super();
		this.clazz = clazz;
		this.originTemplateId = templateId ;
		this.idList = idList ;
		this.valuesList = valuesList ;
	}
	
	
	public Delta(
			Class<T> clazz,
			int templateId,
			int[] idArray,
			T[] valuesArray) {
		
		super();
		this.clazz = clazz;
		this.originTemplateId = templateId ;
		
		this.idList = new ArrayList<Integer>() ;
		for( int id : idArray )
			this.idList.add(id) ;
		
		this.valuesList = new ArrayList<T>( Arrays.asList(valuesArray)) ;
	}

	Class<T> clazz ;
	private int originTemplateId ;
	private int collectionId ;
	private List<Integer> idList ;
	private List<T> valuesList ;
	private int id ;
	
	@Override
	public Date getDate() {
		INote note = getNote() ;
		return note != null ? note.getDate() : null ;
	}

	@Override
	public T getValue(ICollectionMember<?> member) {		
		int id = member.getId() ;
		int size = idList.size();
		for( int i = 0 ; i < size ; i++ ){
			Integer id_ = idList.get(i);
			if( id != id_ )
				continue ;
			
			return valuesList.get(i);
		}
		return null ;
	}

	@Override
	public ITemplate getTemplate() {
		return BasicNoteRegistry.getInstance().getTemplate(originTemplateId) ;
	}

	@Override
	public INote getNote() {
		ITemplate template = getTemplate();
		return template != null ? template.getNote() : null ;
	}

	@Override
	public List<ICollectionMember<?>> getAffectedMembers() {
		
		if( getCollection() == null )
			return null ;
		
		ArrayList<ICollectionMember<?>> result = new ArrayList<ICollectionMember<?>>() ;
		for( Integer id : idList )
			result.add( getCollection().getMemberById(id) ) ;

		return result ;
	}

	@Override
	public Class<T> getSubjectClass() {
		return clazz;
	}

	@Override
	public IObjectCollection getCollection() {
		return BasicCollectionRegistry.getInstance().getCollection(collectionId) ;
	}

	@Override
	public void setCollection(IObjectCollection container) {
		this.collectionId = container.getId() ;		
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public List<Integer> getAffectedMembersIdList() {
		return idList;
	}

	@Override
	public int getCollectionId() {
		return collectionId ;
	}

}
